<?php
declare (strict_types=1);

namespace app\listener\agent;

use app\event\AgentAddSuccess;
use app\model\Agent;
use app\model\PageSetting;

class AgentAddSuccessTakeoutButt
{
    /**
     * 事件监听处理
     * @param AgentAddSuccess $event
     * @return mixed
     */
    public function handle(AgentAddSuccess $event)
    {
        /**
         * @var Agent
         */
        $agent = $event->agent;

        $pageSettings = PageSetting::query()->where('agent_id', 0)
            ->where('type', PageSetting::TYPE_TACKOUT)
            ->where('source', PageSetting::SOURCE_SYSTEM)
            ->where('status', PageSetting::STATUS_ACTIVE)
            ->select();
        $query = collect($pageSettings);

        //初始化轮播图、金刚区
        if (!$query->isEmpty()) {
            $query->each(function (PageSetting $pageSetting) use ($agent){
                $lunBo = clone $pageSetting;
                $lunBo->id = null;
                $lunBo->created_at = null;
                $lunBo->updated_at = null;
                $lunBo->agent_id = $agent->id;
                PageSetting::create($lunBo->toArray());
                unset($lunBo);
            });
        }
        unset($pageSettings);
        unset($query);
    }
}
